package com.jy.common.tool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import com.google.gson.Gson;

// 用于发送HTTP请求到外部接口（这里主要是高德地图接口）的工具类
public class HttpUtil {

    // 使用Gson库来处理JSON数据，将JSON字符串转换为Java对象等
    private static final Gson gson = new Gson();

    // 发送GET请求的方法，参数为请求的URL地址和请求参数（以Map形式传入，方便添加多个参数）
    public static String sendGetRequest(String url, Map<String, Object> params) throws IOException {
        // 如果有请求参数，拼接URL和参数
        if (params!= null &&!params.isEmpty()) {
            StringBuilder paramBuilder = new StringBuilder();
            paramBuilder.append("?");
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                paramBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            url = url + paramBuilder.substring(0, paramBuilder.length() - 1);
        }
        // 创建URL对象
        StringBuilder response = getStringBuilder(url);
        // 返回响应内容（一般是JSON格式的字符串）
        return response.toString();
    }

    private static StringBuilder getStringBuilder(String url) throws IOException {
        URL obj = new URL(url);
        // 打开连接
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        // 设置请求方法为GET
        con.setRequestMethod("GET");

        // 获取响应状态码
        int responseCode = con.getResponseCode();
        StringBuilder response = new StringBuilder();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 如果响应状态码是200（表示请求成功），读取响应内容
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
            String inputLine;
            while ((inputLine = in.readLine())!= null) {
                response.append(inputLine);
            }
            in.close();
        }
        return response;
    }
}